package com.handyshop.mall.basic.core.exception;

import cn.hutool.json.JSONUtil;
import com.handyshop.mall.basic.core.constants.ErrorEnum;
import com.handyshop.mall.basic.core.vo.ResultVo;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无效token或格式不对类
 *
 * @author hs
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    /**
     * 无效token或格式不对类
     *
     * @param request       request
     * @param response      response
     * @param authException authException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        try {
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(
                    JSONUtil.parse(ResultVo.failure(ErrorEnum.OAUTH_TOKEN_FAILURE)).toString()
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}